#!/usr/bin/lua
require("apm_core")

-- 注意apm_global.lua里定义的变量/函数,不要重复定义

-- 检查平均响应时间超大的问题
-- return 1: 该数据不上报;其它:上报数据
function post_analysis()
    local s_em_type;
    local i_syn_time_us;
    local i_send_time_us;
    local i_server_time_us;
    local i_download_time_us;
    local s_title;
    local ApmData = require("ApmData");

    s_em_type = ApmData.getMsgType();
    if s_em_type == nil then
        return ;
    end

    -- 不是响应的返回
    if s_em_type ~= 1 then
        return ;
    end

    i_syn_time_us = ApmData.getField("connection.syn_time_us", 1);
    if i_syn_time_us == nil then
        i_syn_time_us = 0;
    end

    i_send_time_us = ApmData.getField("request.send_time_us", 1);
    if i_send_time_us == nil then
        i_send_time_us = 0;
    end

    i_server_time_us = ApmData.getField("response.server_time_us", 1);
    if i_server_time_us == nil then
        i_server_time_us = 0;
    end

    i_download_time_us = ApmData.getField("response.download_time_us", 1);
    if i_download_time_us == nil then
        i_download_time_us = 0;
    end

    s_title = ApmData.getField("transaction.title", 1);
    if s_title == nil then
        s_title = "";
    end

    if type (i_syn_time_us) ~= "number" then
        i_syn_time_us = tonumber(i_syn_time_us);
    end

    if type (i_send_time_us) ~= "number" then
        i_send_time_us = tonumber(i_send_time_us);
    end

    if type (i_server_time_us) ~= "number" then
        i_server_time_us = tonumber(i_server_time_us);
    end

    if type (i_download_time_us) ~= "number" then
        i_download_time_us = tonumber(i_download_time_us);
    end

    local i_max = 150000000;
    local i_total = i_syn_time_us + i_send_time_us + i_server_time_us + i_download_time_us;
    if i_total > i_max or i_total == 0 or i_syn_time_us < 0 or i_send_time_us < 0 or i_server_time_us < 0 or i_download_time_us < 0 then
        logDebug("Protocol:[%s] Title:[%s] reponse_time > %d (total:[%d] syn:[%d] send:[%d] server:[%d] download:[%d])",
            ApmData.getL7proto(),
            s_title,
            i_max,
            i_total,
            i_syn_time_us,
            i_send_time_us,
            i_server_time_us,
            i_download_time_us
        );
    end

	return ;
end
